package com.czm.art_light.service.impl;

import com.czm.art_light.config.WxConfig;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.service.WxService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信 服务类
 */
@Service
@Slf4j
public class WxServiceImpl implements WxService {

    private static final String WX_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取用户的登录请求信息，根据code获取openid
     */
    @Override
    public String getWxOpenId(String jsCode) {
        try {
            // 构建请求 URL
            String url = UriComponentsBuilder.fromHttpUrl(WX_SESSION_URL)
                    .queryParam("appid", wxConfig.getAppId())
                    .queryParam("secret", wxConfig.getSecret())
                    .queryParam("js_code", jsCode)
                    .queryParam("grant_type", wxConfig.getGrantType())
                    .toUriString();

            // 接收响应为字符串
            String responseString = restTemplate.getForObject(url, String.class);

            // 手动解析为 HashMap
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap response = objectMapper.readValue(responseString, HashMap.class);


            // 检查是否存在错误码
            if (response == null || response.get("errcode") != null) {
                log.error("根据登录用户的code获取openid异常：{}", response);
                throw new BusinessException(ArtErrorCodeEnum.USER_ACCOUNT_EXCEPTION);
            }

            // 提取 openId
            String openId = (String) response.get("openid");
            if (openId == null || openId.isEmpty()) {
                log.error("根据登录用户的code获取openid异常：{}", response);
                throw new BusinessException(ArtErrorCodeEnum.USER_ACCOUNT_EXCEPTION);
            }
            return openId;
        } catch (JsonProcessingException e) {
            log.error("JSON 解析异常：{}", e.getMessage(), e);
            throw new BusinessException(ArtErrorCodeEnum.SYSTEM_PARSE_ERROR);
        }
    }
}
